package com.github.binarywang.demo.wx.mp.handler;

import com.github.binarywang.demo.wx.mp.builder.TextBuilder;
import com.github.binarywang.demo.wx.mp.config.CommonConstant;
import com.github.binarywang.demo.wx.mp.utils.StorageUtils;

import org.springframework.stereotype.Component;

import java.util.Map;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;

/**
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@Component
public class ScanHandler extends AbstractHandler {

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMpXmlMessage, Map<String, Object> map,
                                    WxMpService wxMpService, WxSessionManager wxSessionManager) throws WxErrorException {
        // 扫码事件处理
        String str = StorageUtils.getStr(wxMpXmlMessage.getEventKey());
        if (StrUtil.isNotEmpty(str)) {
            JSONObject entries = JSONUtil.parseObj(str);
            String url = entries.getStr("url");
            String appId = entries.getStr("appId");
            if (StrUtil.isNotEmpty(url) && StrUtil.isNotEmpty(appId)) {
                url = wxMpService.switchoverTo(appId).getOAuth2Service().buildAuthorizationUrl(url, CommonConstant.AUTH_USERINFO, "");
                return new TextBuilder().build(String.format("<a href=\"%s\">点击参加活动</a>", url), wxMpXmlMessage, wxMpService);
            }
        }
        return null;
    }
}
